package com.xxwy.bean.initialization;

import com.xxwy.bean.DefaultUserFactory;
import com.xxwy.bean.UserFactory;
import com.xxwy.bean.UserRepository;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;

/**
 * @author wy
 * @date 2020/4/21 15:54
 */
@Configuration
public class BeaInitializationDemo {

    public static void main(String[] args) throws InterruptedException {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
        applicationContext.register(BeaInitializationDemo.class);
        applicationContext.refresh();

        System.out.println("spring上下文ok");
        // @Lazy 没有getBean就不会实例化，初始化即：new， PostConstruct ，initializingBean， initMethod 都不会执行。
        // DefaultUserFactory factory = applicationContext.getBean("defaultUserFactory", DefaultUserFactory.class);
//    UserRepository repository = applicationContext.getBean(UserRepository.class);
//    System.out.println(repository);

        applicationContext.close();

        System.out.println("spring上下文bye");

        // DefaultUserFactory factory1 = new DefaultUserFactory();

        //factory = null;
        //factory1 = null;
        System.gc();
        Thread.sleep(10000);
    }

    /**
     * @Lazy 没用getBean() 不会实例化（new 方法）没有初始化
     * @return DefaultUserFactory
     */
    @Lazy
    @Bean(initMethod = "initUserFactory",destroyMethod = "destroyUserFactory")
    public DefaultUserFactory defaultUserFactory(){
        return new DefaultUserFactory();
    }

    /**
     * 依赖查找，还是getBean了的。so会初始化
     * @param userFactory  DefaultUserFactory
     * @return UserRepository
     */
    @Bean
    public UserRepository userRepository(UserFactory userFactory){
        return new UserRepository(userFactory);
    }

}
